package main

import (
	"aliyundns/config"
	"aliyundns/loger"
	"aliyundns/utils"
	"fmt"
	"github.com/kardianos/service"
	go_logger "github.com/phachon/go-logger"
	"log"
	"time"
)

type myProgram struct{}

func (p *myProgram) Start(s service.Service) error {
	// 启动服务时执行的操作
	go p.run()
	return nil
}

func (p *myProgram) run() {
	// 在这里编写你的服务逻辑代码
	RunAli()
	log.Println("Service running...")
}

func (p *myProgram) Stop(s service.Service) error {
	// 停止服务时执行的操作
	log.Println("Service stopped.")
	return nil
}

func RunAli() {
	c := config.Config{}
	cfg, err := c.GetConfig()
	if err != nil {
		loger.OutToFile(fmt.Sprintf("读取配置文件错误：%v\n", err))
		return
	}
	for {
		ip, err := utils.GetPubLicIp(cfg.Ali.Url)
		if err != nil {
			loger.OutToFile(fmt.Sprintf("%v", err))
			continue
		}
		client, err := utils.CreateAliyunClient(cfg.Ali.RegionId, cfg.Ali.AccessKeyId, cfg.Ali.AccessKeySecret)
		if err != nil {
			loger.OutToFile(fmt.Sprintf("创建阿里云DNS客户端失败%v", err))
			continue
		}
		oldIp, err := utils.UpdateDns(client, cfg.Ali.DomainName, cfg.Ali.RecordType, ip, cfg.Ali.RecordName)
		if err != nil {
			loger.OutToFile(fmt.Sprintf("%v\n", err))
		} else {
			loger.OutToFile(fmt.Sprintf("更新DNS记录成功,IP 记录由 %v 被更新为：%v", oldIp, ip))
			msg := "<h1>您的阿里云域名【" + cfg.Ali.DomainName + "】IP解析记录由<h1>" + "\n" + oldIp + "\n" + "<h1>被更新为<h1>" + "\n" + ip
			err = utils.SendMail(cfg.Mail.SmtpServer, cfg.Mail.FromMail, cfg.Mail.FromPassword, cfg.Mail.ToMail, cfg.Mail.Subject, msg, cfg.Mail.Port, cfg.Mail.InsecureSkipVerify)
			if err != nil {
				loger.OutToFile(fmt.Sprintf("发送邮件失败：%v", err))
			}
		}
		time.Sleep(time.Duration(cfg.Ali.Sleep) * time.Minute) // 每10分钟检查一次
	}
}

func main() {
	// init logger
	loger.Logger = go_logger.NewLogger()
	loger.CreateLogFile()

	svcConfig := &service.Config{
		Name:        "AliService",
		DisplayName: "Ali_dns_Service",
		Description: "This is a aliyun dns service written in Go.",
	}

	prg := &myProgram{}
	s, err := service.New(prg, svcConfig)
	if err != nil {
		log.Fatal(err)
	}

	// 以服务方式运行
	if err = s.Run(); err != nil {
		log.Fatal(err)
	}
}
